package com.a1573595.musicplayer

import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.a1573595.musicplayer.playSong.PlaySongActivity
import com.a1573595.musicplayer.player.PlayerService
import timber.log.Timber

class PlayerApplication : Application() {
    var playerService: PlayerService? = null    //其他组件可以通过 PlayerApplication 全局访问这个实例。
    var playSongActivity: PlaySongActivity? = null

    override fun onCreate() {
        super.onCreate()
        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }
        initPlayerService()
    }

    private fun initPlayerService() {
        val intent = Intent(this, PlayerService::class.java)
        startService(intent)
        bindService(intent, object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                val binder = service as PlayerService.LocalBinder
                playerService = binder.service
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                playerService = null
            }
        }, Context.BIND_AUTO_CREATE)
    }
}